/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * This file is part of FileExplorer.
 *
 * FileExplorer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FileExplorer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SwiFTP.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.dlna.client.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import com.dlna.client.enity.DirInfo;
import com.dlna.client.enity.FileInfo;
import com.dlna.client.enity.PictureInfo;

public class Util {
	private static final String TAG = "Util";

	public static boolean isSDCardReady() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	public static void createClientDir() {
		File file = new File(Constant.APP_PATH);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public static boolean deleteFiles(ArrayList<FileInfo> files) {
		for (FileInfo f : files) {
			deleteFile(f);
		}
		return true;
	}

	protected static void deleteFile(FileInfo f) {
		if (f == null) {
			Log.e(TAG, "DeleteFile: null parameter");
			return;
		}

		File file = new File(f.filePath);
		boolean directory = file.isDirectory();
		if (directory) {
			for (File child : file.listFiles()) {
				deleteFile(Util.GetFileInfo(child.getAbsolutePath(), null));
			}
		}
		file.delete();

		Log.v(TAG, "DeleteFile >>> " + f.filePath);
	}

	public static void deleteFile(File file) {
		if (file == null) {
			Log.e(TAG, "DeleteFile: null parameter");
			return;
		}

		boolean directory = file.isDirectory();
		if (directory) {
			for (File child : file.listFiles()) {
				deleteFile(child);
			}
		}
		file.delete();

		Log.v(TAG, "DeleteFile >>> " + file.getAbsolutePath());
	}

	/**
	 * 复制一个新的列表
	 * 
	 * @param files
	 * @return
	 */
	public static ArrayList<FileInfo> copyFileList(ArrayList<FileInfo> files) {
		ArrayList<FileInfo> fileInfos = new ArrayList<FileInfo>();
		for (FileInfo f : files) {
			fileInfos.add(f);
		}
		return fileInfos;
	}

	public static ArrayList<FileInfo> getDiffrent(ArrayList<FileInfo> list1,
			ArrayList<FileInfo> list2) {
		ArrayList<FileInfo> diff = new ArrayList<FileInfo>();
		for (FileInfo str : list1) {
			if (!list2.contains(str)) {
				diff.add(str);
			}
		}
		return diff;
	}

	public static boolean checkDiffrent(ArrayList<FileInfo> list1,
			ArrayList<FileInfo> list2) {
		for (FileInfo str : list1) {
			if (!list2.contains(str)) {
				return true;
			}
		}
		for (FileInfo str : list2) {
			if (!list1.contains(str)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 复制一个新的列表
	 * 
	 * @param files
	 * @return
	 */
	public static void copyFileList(ArrayList<FileInfo> files,
			ArrayList<FileInfo> des) {
		des.clear();
		for (FileInfo f : files) {
			des.add(f);
		}
	}

	public static void getFileInfos(final List<FileInfo> list, File file,
			final Context context) {
		file.listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {

				if (file.isDirectory()) {
					getFileInfos(list, file, context);
				} else {
					list.add(GetFileInfo(file.getAbsolutePath(), context));
				}
				return false;
			}
		});

	}

	public static void getDirectoryNames(final List<DirInfo> list, File file) {
		list.clear();
		file.listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				// TODO Auto-generated method stub
				String name = file.getName();
				int i = name.lastIndexOf('.');
				if (i == -1 && file.isDirectory() && !file.getName().equals("cache")) {
					list.add(getDirInfo(file.getAbsolutePath()));
					return true;
				}else {
					return false;
				}
			}
		});
	}

	public static DirInfo getDirInfo(String filePath) {
		DirInfo dirInfo = new DirInfo();
		dirInfo.dirFullPath = filePath;
		File file = new File(filePath);
		dirInfo.dirName = file.getName();
		return dirInfo;
	}

	/**
	 * 获取图片文件
	 * 
	 * @param list
	 * @param file
	 */
	public static void getPictureFile(final List<FileInfo> list, File file, final Context context) {
//		list.clear();
		file.listFiles(new FileFilter() {
			@Override
			public boolean accept(File ifile) {
				String name = ifile.getName();
				int i = name.lastIndexOf('.');
				if (i != -1) {
					name = name.substring(i).toLowerCase();
					if (name.equals(".jpg") || name.equals(".gif") || name.equals(".png") || name.equals(".jpeg")) {
						list.add(GetFileInfo(ifile.getAbsolutePath(), context));
						return true;
					}
				} else if (ifile.isDirectory()) {
					getPictureFile(list, ifile, context);
				}
				return false;
			}
		});
	}
	
	public static ArrayList<PictureInfo> getPictureFile(File file ){
		final ArrayList<PictureInfo> list = new ArrayList<PictureInfo>();
		file.listFiles(new FileFilter() {
			@Override
			public boolean accept(File arg0) {
				String extensionName;
				String name = arg0.getName();
				int i = name.lastIndexOf(".");
				if(i != -1){
					extensionName = name.substring(i+1).toLowerCase();
					name = name.substring(0, i);
					if(extensionName.equals("jpg") || extensionName.equals("gif")||extensionName.equals("png")|| extensionName.equals("jpeg") ){
						PictureInfo info = new PictureInfo(arg0.getAbsolutePath(), name, arg0.getParent()+ File.separator + name +".txt");
						L.d("txtFilePath------->"+info.txtFilePath);
						info.text = FileTools.ReadTxtFile(info.txtFilePath);
						list.add(info);
						
						return true;
					}
				}
				
				return false;
			}
		});
		return list;
	}

	
	
	
	

	public static void getVideoFile(final List<FileInfo> list, File file,
			final Context context) {
		list.clear();
		file.listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				String name = file.getName();

				int i = name.lastIndexOf('.');

				if (i != -1) {
					name = name.substring(i).toLowerCase();

					if (name.equals(".mp4")

					|| name.equals(".3gp")

					// || name.equals(".wmv")
					//
					// || name.equals(".rmvb")

							|| name.equals(".flv")

							|| name.equals(".3gpp")) {
						list.add(GetFileInfo(file.getAbsolutePath(), context));
						return true;
					}
				} else if (file.isDirectory()) {
					getVideoFile(list, file, context);
				}
				return false;
			}
		});

	}

	/**
	 * 获取所有文件
	 * 
	 * @param list
	 * @param file
	 * @param context
	 */
	public static void getAllFile(final List<FileInfo> list, File file,
			final Context context) {
		file.listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {

				// sdCard找到视频名称

				String name = file.getName();

				int i = name.lastIndexOf('.');

				if (i != -1) {
					name = name.substring(i).toLowerCase();

					if (name.equals(".jpg")

					|| name.equals(".gif")

					|| name.equals(".png")

					|| name.equals(".jpeg")

					|| name.equals(".mp4")

					|| name.equals(".3gp")

					|| name.equals(".flv")

					|| name.equals(".3gpp")

					) {
						list.add(GetFileInfo(file.getAbsolutePath(), context));

						return true;
					}

				} else if (file.isDirectory()) {
					getAllFile(list, file, context);
				}
				return false;
			}
		});
	}

	public static FileInfo GetFileInfo(String httpUrl) {
		FileInfo lFileInfo = new FileInfo();
		lFileInfo.httpUrl = httpUrl;
		lFileInfo.fileName = Util.getNameFromFilepath(httpUrl);
		// lFileInfo.filePath = Constant.APP_PATH + Constant.ROOT_PATH
		// + lFileInfo.fileName;
		return lFileInfo;
	}

	public static FileInfo GetFileInfo(String filePath, Context context) {
		File lFile = new File(filePath);
		if (!lFile.exists())
			return null;

		FileInfo lFileInfo = new FileInfo();
		lFileInfo.canRead = lFile.canRead();
		lFileInfo.canWrite = lFile.canWrite();
		lFileInfo.isHidden = lFile.isHidden();
		lFileInfo.fileName = Util.getNameFromFilepath(filePath);
		lFileInfo.ModifiedDate = lFile.lastModified();
		lFileInfo.IsDir = lFile.isDirectory();
		lFileInfo.filePath = filePath;
		lFileInfo.fileSize = lFile.length();
		return lFileInfo;
	}

	public static String getNameFromFilename(String filename) {
		int dotPosition = filename.lastIndexOf('.');
		if (dotPosition != -1) {
			return filename.substring(0, dotPosition);
		}
		return "";
	}

	public static String getNameFromFilepath(String filepath) {
		int pos = filepath.lastIndexOf('/');
		if (pos != -1) {
			return filepath.substring(pos + 1);
		}
		return "";
	}

	/**
	 * 检测是否为WIFI网络
	 * 
	 * @param context
	 * @return
	 */
	public static boolean checkIfWifiEnable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}

		return false;
	}

	/**
	 * 判断本地文件列表是否含有该文件
	 */
	public static FileInfo checkIfcontains(String url, ArrayList<FileInfo> list) {
		FileInfo fileInfo = Util.GetFileInfo(url);
		if (list.contains(fileInfo)) {
			int position = list.indexOf(fileInfo);
			fileInfo = list.get(position);
		}
		return fileInfo;
	}

	public static void readFileFromSdcard(File fileName,
			ArrayList<FileInfo> remoteFile) throws Exception {
		remoteFile.clear();
		BufferedReader bufferedReader = null;
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					fileName), "GBK");
			bufferedReader = new BufferedReader(read);

			String httpUrl = "";
			while ((httpUrl = bufferedReader.readLine()) != null) {
				remoteFile.add(Util.GetFileInfo(httpUrl));
			}
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static boolean interceptFlag = false;

	/**
	 * 下载文件
	 * 
	 * @param url
	 * @param outputFile
	 * @param mHandler
	 * @throws Exception
	 */
	public static void downloadByUrl(String url, File outputFile,
			Handler mHandler) throws Exception {
		// 判断是否挂载了SD卡
		// if (!isSDCardReady())
		// {
		// Log.e(TAG, "SDcard未挂载");
		// return;
		// }
		File path = new File(Constant.APP_PATH);
		if (!path.exists()) {
			path.mkdirs();
		}

		// 是否已下载更新文件
		if (outputFile.exists()
				&& (!outputFile.getName().equals(Constant.SYNCFILE_NAME))) {
			Log.e(TAG, "------>文件已存在 " + url);
			return;
		}
		FileOutputStream fos = null;
		InputStream is = null;
		try {
			Log.e(TAG, "------>下载文件名 " + outputFile.getAbsolutePath());
			File tmpName = new File(Constant.APP_PATH
					+ url.substring(url.lastIndexOf("/")) + ".tmp");
			// 输出临时下载文件
			fos = new FileOutputStream(tmpName);

			url = URLEncoder.encode(url, "UTF-8");
			url = url.replaceAll("\\+", "%20");
			url = url.replaceAll("%2F", "/");
			url = url.replaceAll("%3A", ":");
			URL downLoadUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) downLoadUrl
					.openConnection();
			conn.setConnectTimeout(10000);
			conn.connect();
			is = conn.getInputStream();
			// 显示文件大小格式：2个小数点显示
			byte buf[] = new byte[1024];

			do {
				int numread = is.read(buf);
				if (numread <= 0) {
					// 下载完成 - 将临时下载文件转成APK文件
					if (tmpName.renameTo(outputFile)) {
						// 下载完成
						// mHandler.sendEmptyMessage(DOWN_OVER);
					}
					break;
				}
				fos.write(buf, 0, numread);
			} while (!interceptFlag);// 点击取消就停止下载
		} finally {
			if (fos != null)
				fos.close();
			if (is != null)
				is.close();
		}
	}

	public static final int bytes2Int(byte[] b, int pos) {
		return (b[pos] << 24) + ((b[pos + 1] & 0xFF) << 16)
				+ ((b[pos + 2] & 0xFF) << 8) + (b[pos + 3] & 0xFF);
	}
	 public static boolean isNotBlank(String str) {
	        if (str != null && str.trim().length() > 0){
	            return  true;
	        }else{
	            return false;
	        }
	    }
}
